package ferp.center.server.servlet;

import ferp.center.server.Action;
import ferp.center.server.entity.Rating;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * User: igorgok
 * Date: 12/6/12 3:49 PM
 */
public class RatingDataGet extends HttpServlet
{
  protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/plain");
    response.setCharacterEncoding(UTF8);

    final PrintWriter pw = response.getWriter();
    final int start = Integer.valueOf(request.getParameter("s"));
    final int chunk = Integer.valueOf(request.getParameter("c"));

    Action.execute(request, new Action.Task()
    {
      @SuppressWarnings("unchecked")
      public void run(EntityManager em, HttpServletRequest request) throws IOException
      {
        int count = start;
        List<Rating> ratings = em.createQuery("SELECT r FROM Rating r").setMaxResults(chunk).setFirstResult(start).getResultList();

        for (Rating r : ratings)
        {
          Integer update = r.getUpdate();

          pw.append(String.valueOf(++count)).append(',')
            .append(String.valueOf(r.getProfile().getKey().getId())).append(',')
            .append(r.getConfiguration()).append(',')
            .append(String.valueOf(r.getSpeed())).append(',')
            .append(String.valueOf(r.getCash())).append(',')
            .append(String.valueOf(r.getPool())).append(',')
            .append(update == null ? "-" : String.valueOf(r.getUpdate())).append('\n');
        }

        pw.flush();
        pw.close();
      }
    });
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
  }

  private static final String UTF8 = "UTF-8";
}
